<template lang="pug">
.view.cp-inv-allot.fix-flex-pos
  //- 查询
  el-form.alt-search(:inline="true")
    el-form-item
      el-select.select-width(v-model="timeType", placeholder="请选择")
        el-option(key="0", label="创建时间", :value="0")
        el-option(key="1", label="更新时间", :value="1")
        el-option(key="2", label="调拨时间", :value="2")
    el-form-item(label="起止时间 :")
      el-date-picker.date-width(
        v-model="dateRange",
        type="daterange",
        unlink-panels,
        start-placeholder="开始日期",
        end-placeholder="结束日期",
        value-format="timestamp",
        :default-time="['00:00:00', '23:59:59']")
    el-form-item(label="状态 :")
      el-select.select-width(v-model="status", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allAllotStatus",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="调出仓库 :")
      el-select.select-width(v-model="outboundStorehouse", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allStorehouse",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="调入仓库 :")
      el-select.select-width(v-model="inboundStorehouse", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allStorehouse",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item(label="仓管员 :")
      el-select.select-width(v-model="keeper", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allKeeper",
          :key="index",
          :label="item.name",
          :value="item.value")
    el-form-item
      el-input(
        v-model="orderNo",
        placeholder="调拨单号",
        suffix-icon="el-icon-search"
        style="width: 320px")
    el-form-item(label="关键字 :")
      el-input(
        v-model="keyWord",
        placeholder="关键字",
        style="width: 160px")
    el-form-item
      el-button(type="primary", @click="search") 搜索
    el-form-item
      el-button(type="primary", @click="creatAllotBill", plain) 新建调拨单
    el-form-item
      el-button(@click="exportReport", plain) 导出
  //- 表格
  .alt-table
    el-table(
      :data="invAllotList",
      highlight-current-row,
      v-loading="loadingAllot",
      @row-dblclick="dbClickRow",
      size="mini",
      height="100%")
      el-table-column(show-overflow-tooltip, type="index", :index="indexMethod", label="序号")
      el-table-column(label="调拨单号")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.orderNo")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.orderNo}}
      el-table-column(show-overflow-tooltip, prop="status", label="状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(allAllotStatus) }}
      el-table-column(show-overflow-tooltip, label="调拨时间")
        template(slot-scope="scope")
          span {{scope.row.transferTime | date-format}}
      el-table-column(show-overflow-tooltip, prop="outboundStorehouse", label="调出仓库")
        template(slot-scope="scope")
          span {{ scope.row.outboundStorehouse | compare-list(allStorehouse) }}
      el-table-column(show-overflow-tooltip, prop="inboundStorehouse", label="调入仓库")
        template(slot-scope="scope")
          span {{ scope.row.inboundStorehouse | compare-list(allStorehouse) }}
      el-table-column(show-overflow-tooltip, prop="nextOutboundOrder", label="关联出库单号")
      el-table-column(show-overflow-tooltip, prop="nextInboundOrder", label="关联入库单号")
      el-table-column(show-overflow-tooltip, prop="keeper", label="仓管员")
        template(slot-scope="scope")
          span {{ scope.row.keeper | compare-list(allKeeper) }}
      el-table-column(show-overflow-tooltip, label="创建时间")
        template(slot-scope="scope")
          span {{scope.row.creationTime | date-format}}
      el-table-column(show-overflow-tooltip, prop="remark", label="备注")
      el-table-column(label="操作", min-width="110px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewInvAllot(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="editInvAllot(scope.row)")
          el-tooltip(content="复制")
            i.icon-act.el-icon-hy-copy(@click="copyInvAllot(scope.row)")
          el-dropdown
            i.icon-act.el-icon-more
            el-dropdown-menu(slot="dropdown", class="inv-act-drop")
              el-dropdown-item.act-item(@click.native="submitInvOrder(scope.row)")
                i.icon-act.el-icon-hy-submit-o
                span 提交
              el-dropdown-item.act-item(@click.native="backInvOrder(scope.row)")
                i.icon-act.el-icon-hy-back
                span 撤回
              el-dropdown-item.act-item(@click.native="deleteInvOrder(scope.row, scope.$index)")
                i.icon-act.el-icon-delete
                span 删除
              el-dropdown-item.act-item(@click.native="printInvOrder(scope.row)")
                i.icon-act.el-icon-hy-print
                span 打印
  //- 分页
  el-pagination.alt-pagination(
    background,
    layout="total, prev, pager, next, jumper",
    prev-text="上一页",
    next-text="下一页",
    @current-change="handleCurrentChange",
    :current-page="pageNum",
    :page-size="pageSize",
    :total="totalNum")
  //- 新建调拨单
  allotForm(
    :title="allotDialogTitle",
    :visible.sync="showAllotDialog",
    :is-edit="isEdit",
    :parent-data="formData",
    @submit="onFormSubmit",
    @close="showAllotDialog = false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import AllotApi from '@/api/inventory/inbound';
import allotForm from './allotForm';

export default {
  name: 'invallot',
  data() {
    return {
      loadingAllot: true,
      invAllotList: [],
      pageNum: 1,
      pageSize: 20,
      totalNum: 0,
      // 搜索条件
      timeType: 0,
      dateRange: [],
      status: null,
      outboundStorehouse: null,
      inboundStorehouse: null,
      keeper: null,
      orderNo: null,
      keyWord: null,
      // 弹出框
      allotDialogTitle: '新建调拨单',
      showAllotDialog: false,
      // 能编辑  true--能 false--不能
      isEdit: true,
      // 新建时初始数据
      formData: {
        transferTime: new Date(),
        skuArray: [{ canEdit: false }]
      },
      // 搜索下拉框
      allAllotStatus: []
    };
  },
  computed: {
    ...mapGetters({
      creator: 'employeeId',
      allStorehouse: 'storeSelect',
      allKeeper: 'keeperSelect'
    })
  },
  components: {
    allotForm
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'transfer' }).then((statusList) => {
      this.allAllotStatus = statusList;
    });
  },
  mounted() {
    this.loadAllotList();
  },
  methods: {
    indexMethod (i) {
      return ((this.pageNum - 1) * this.pageSize) + (i + 1);
    },
    filterParams() {
      const params = {
        creator: this.creator,
        status: this.status,
        outboundStorehouse: this.outboundStorehouse,
        inboundStorehouse: this.inboundStorehouse,
        keeper: this.keeper,
        orderNo: this.orderNo,
        keyWord: this.keyWord,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.timeType === 0 && this.dateRange && this.dateRange[0]) {
        params.startCreationTime = this.dateRange[0];
        params.endCreationTime = this.dateRange[1];
      }
      if (this.timeType === 1 && this.dateRange && this.dateRange[0]) {
        params.startUpdateTime = this.dateRange[0];
        params.endUpdateTime = this.dateRange[1];
      }
      if (this.timeType === 2 && this.dateRange && this.dateRange[0]) {
        params.startTransferTime = this.dateRange[0];
        params.endTransferTime = this.dateRange[1];
      }
      for (const key in params) {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      }
      return params;
    },
    // 取得调拨数据
    loadAllotList() {
      this.loadingAllot = true;
      const params = this.filterParams();
      AllotApi.getAllotList(params).then((result) => {
        if (result.status === 0 && result.obj) {
          this.invAllotList = result.obj.records;
          this.totalNum = result.obj.totalNum;
        } else {
          this.$message.error(result.comment || '获取数据失败');
        }
        this.loadingAllot = false;
      }).catch((error) => {
        this.loadingAllot = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadAllotList();
    },
    // 新建
    creatAllotBill() {
      this.allotDialogTitle = '新建调拨单';
      this.formData = {
        orderNo: null,
        demand1LevelDept: null,
        demand2LevelDept: null,
        demander: null,
        keeper: null,
        outboundStorehouse: null,
        inboundStorehouse: null,
        transferTime: new Date(),
        nextInboundOrder: null,
        nextOutboundOrder: null,
        remark: null,
        skuArray: [{ canEdit: true }]
      };
      this.showAllotDialog = true;
      this.isEdit = true;
    },
    dbClickRow(currentrow) {
      this.viewInvAllot(currentrow);
    },
    // 查看
    viewInvAllot(currentrow) {
      this.allotDialogTitle = '查看调拨单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AllotApi.detailInvAllot(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: currentrow.orderNo
          };
          this.showAllotDialog = true;
          this.isEdit = false;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 日期生成Date对象
    filterDate(data = []) {
      if (!data) {
        return [];
      }
      return data.map((item) => {
        if (item.productionDate) {
          const productionDate = new Date(item.productionDate).getTime();
          return { ...item, productionDate };
        }
        return item;
      });
    },
    // 编辑
    editInvAllot(currentrow) {
      this.allotDialogTitle = '编辑调拨单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AllotApi.detailInvAllot(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: currentrow.orderNo,
            transferTime: new Date(res.obj.transferTime),
            skuArray: this.filterDate(res.obj.skuArray)
          };
          this.showAllotDialog = true;
          this.isEdit = true;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 复制
    copyInvAllot(currentrow) {
      this.allotDialogTitle = '新建调拨单';
      const params = {
        orderNo: currentrow.orderNo
      };
      AllotApi.detailInvAllot(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.formData = {
            ...res.obj,
            orderNo: null,
            transferTime: new Date(res.obj.transferTime),
            skuArray: this.filterDate(res.obj.skuArray)
          };
          this.showAllotDialog = true;
          this.isEdit = true;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 保存提交成功
    onFormSubmit(data) {
      if (data.isNew) {
        // 新增
        this.invAllotList.unshift({});
        this.$set(this.invAllotList, 0, data);
        this.totalNum = this.totalNum + 1;
      } else {
        const index = this.invAllotList.findIndex(item => item.orderNo === data.orderNo);
        this.$set(this.invAllotList, index, data);
      }
    },
    // 导出
    exportReport() {
      console.log('导出exportReport');
    },
    // 页码改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.loadAllotList();
    },
    // 提交
    submitInvOrder(currentRow) {
      const params = {
        orderNo: currentRow.orderNo
      };
      AllotApi.submitInvAllot(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '提交成功', type: 'success' });
          currentRow.status = res.obj;
        } else {
          this.$message.error(res.comment || '提交失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 撤回
    backInvOrder(currentRow) {
      const params = {
        orderNo: currentRow.orderNo
      };
      AllotApi.backInvAllot(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '撤回成功', type: 'success' });
          currentRow.status = res.obj;
        } else {
          this.$message.error(res.comment || '撤回失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 删除
    deleteInvOrder(currentRow, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          orderNo: currentRow.orderNo
        };
        AllotApi.deleteInvAllot(params).then((res) => {
          if (res.status === 0) {
            this.invAllotList.splice(index, 1);
            this.totalNum = this.totalNum - 1;
            this.$message({ message: '删除成功', type: 'success' });
          } else {
            this.$message.error(res.comment || '删除失败');
          }
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    // 打印
    printInvOrder(currentRow) {
      console.log('print', currentRow);
    }
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 104px
$SELECTWIDTH: 100px
.cp-inv-allot
  .alt-search
    height: $SEARCHHEIGHT
    padding: 12px 0 12px 16px
    overflow-x: auto
    overflow-y: hidden
    .select-width
      width: $SELECTWIDTH
    .date-width
      width: 260px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      margin-left: 6px
      padding-right: 6px
    .el-date-editor .el-range__close-icon
      width: 20px
    .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label
      height: 32px
  .alt-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: 56px
    left: 16px
    right: 16px
    overflow-x: hidden
    overflow-y: auto
    &::before
      display: none
    .icon-act
      font-size: 16px
      font-weight: 500
      cursor: pointer
      margin-left: 3px
      margin-right: 3px
      &:hover
        color: #5D9BFB
  .el-table
    th, td
      text-align: center
  .alt-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
.inv-act-drop
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: -3px
    margin-right: 6px
</style>
